const express = require('express');
const router = express.Router();
const Student = require('../models/Student');
const { generateAIReport } = require('../services/aiService');

// 获取统计分析数据
router.get('/statistics', async (req, res) => {
  try {
    const { class: className, course: courseName } = req.query;
    
    // 构建查询条件
    const query = className ? { class: className } : {};
    
    // 查询所有符合条件的学生
    const students = await Student.find(query);
    
    if (students.length === 0) {
      return res.json({
        success: true,
        data: {
          total: 0,
          average: 0,
          max: 0,
          min: 0,
          passRate: 0,
          excellentRate: 0,
          goodRate: 0,
          mediumRate: 0,
          passOnlyRate: 0,
          failRate: 0,
          distribution: {
            excellent: 0,
            good: 0,
            medium: 0,
            pass: 0,
            fail: 0
          }
        }
      });
    }
    
    // 提取成绩数据（如果指定课程，只统计该课程）
    let scores = [];
    students.forEach(student => {
      if (student.scores && student.scores.length > 0) {
        if (courseName) {
          const courseScore = student.scores.find(s => s.courseName === courseName);
          if (courseScore) scores.push(courseScore.score);
        } else {
          // 如果没有指定课程，计算每个学生的平均分
          const avgScore = student.scores.reduce((sum, s) => sum + s.score, 0) / student.scores.length;
          scores.push(avgScore);
        }
      }
    });
    
    if (scores.length === 0) {
      return res.json({
        success: true,
        data: {
          total: 0,
          average: 0,
          max: 0,
          min: 0,
          passRate: 0,
          excellentRate: 0,
          goodRate: 0,
          mediumRate: 0,
          passOnlyRate: 0,
          failRate: 0,
          distribution: {
            excellent: 0,
            good: 0,
            medium: 0,
            pass: 0,
            fail: 0
          },
          courseName: courseName || '平均成绩'
        }
      });
    }
    
    // 计算统计数据
    const total = scores.length;
    const sum = scores.reduce((a, b) => a + b, 0);
    const average = (sum / total).toFixed(2);
    const max = Math.max(...scores);
    const min = Math.min(...scores);
    
    // 计算各等级人数
    const excellent = scores.filter(s => s >= 90).length;
    const good = scores.filter(s => s >= 80 && s < 90).length;
    const medium = scores.filter(s => s >= 70 && s < 80).length;
    const pass = scores.filter(s => s >= 60 && s < 70).length;
    const fail = scores.filter(s => s < 60).length;
    
    // 计算比率
    const passRate = (((total - fail) / total) * 100).toFixed(2);
    const excellentRate = ((excellent / total) * 100).toFixed(2);
    const goodRate = ((good / total) * 100).toFixed(2);
    const mediumRate = ((medium / total) * 100).toFixed(2);
    const passOnlyRate = ((pass / total) * 100).toFixed(2);
    const failRate = ((fail / total) * 100).toFixed(2);
    
    res.json({
      success: true,
      data: {
        total,
        average: Number(average),
        max,
        min,
        passRate: Number(passRate),
        excellentRate: Number(excellentRate),
        goodRate: Number(goodRate),
        mediumRate: Number(mediumRate),
        passOnlyRate: Number(passOnlyRate),
        failRate: Number(failRate),
        distribution: {
          excellent,
          good,
          medium,
          pass,
          fail
        },
        classInfo: className || '全部班级',
        courseName: courseName || '平均成绩'
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '统计分析失败',
      error: error.message
    });
  }
});

// 获取成绩排名
router.get('/ranking', async (req, res) => {
  try {
    const { class: className, course: courseName, limit = 100 } = req.query;
    
    const query = className ? { class: className } : {};
    const students = await Student.find(query).select('studentId name class scores');
    
    // 计算每个学生的成绩
    const studentsWithScore = students.map(student => {
      let score = 0;
      if (student.scores && student.scores.length > 0) {
        if (courseName) {
          const courseScore = student.scores.find(s => s.courseName === courseName);
          score = courseScore ? courseScore.score : 0;
        } else {
          // 计算平均分
          score = student.scores.reduce((sum, s) => sum + s.score, 0) / student.scores.length;
        }
      }
      return {
        _id: student._id,
        studentId: student.studentId,
        name: student.name,
        class: student.class,
        score: Number(score.toFixed(2))
      };
    }).filter(s => s.score > 0) // 过滤没有成绩的学生
      .sort((a, b) => b.score - a.score) // 按成绩降序
      .slice(0, Number(limit));
    
    // 添加排名
    const rankedStudents = studentsWithScore.map((student, index) => ({
      rank: index + 1,
      ...student
    }));
    
    res.json({
      success: true,
      data: rankedStudents,
      courseName: courseName || '平均成绩'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '排名查询失败',
      error: error.message
    });
  }
});

// 生成AI分析报告
router.post('/ai-report', async (req, res) => {
  try {
    const { class: className, course: courseName, scope = 'class' } = req.body;
    
    // 获取统计数据
    const query = className ? { class: className } : {};
    const students = await Student.find(query);
    
    if (students.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有找到学生数据'
      });
    }
    
    // 提取成绩数据
    let scores = [];
    students.forEach(student => {
      if (student.scores && student.scores.length > 0) {
        if (courseName) {
          const courseScore = student.scores.find(s => s.courseName === courseName);
          if (courseScore) scores.push(courseScore.score);
        } else {
          const avgScore = student.scores.reduce((sum, s) => sum + s.score, 0) / student.scores.length;
          scores.push(avgScore);
        }
      }
    });
    
    if (scores.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有找到成绩数据'
      });
    }
    
    // 计算统计信息
    const total = scores.length;
    const sum = scores.reduce((a, b) => a + b, 0);
    const average = (sum / total).toFixed(2);
    const max = Math.max(...scores);
    const min = Math.min(...scores);
    
    const excellent = scores.filter(s => s >= 90).length;
    const good = scores.filter(s => s >= 80 && s < 90).length;
    const medium = scores.filter(s => s >= 70 && s < 80).length;
    const pass = scores.filter(s => s >= 60 && s < 70).length;
    const fail = scores.filter(s => s < 60).length;
    
    const passRate = (((total - fail) / total) * 100).toFixed(2);
    const excellentRate = ((excellent / total) * 100).toFixed(2);
    
    // 构建统计数据对象
    const statistics = {
      class: className || '全部班级',
      course: courseName || '平均成绩',
      total,
      average: Number(average),
      max,
      min,
      passRate: Number(passRate),
      excellentRate: Number(excellentRate),
      distribution: { excellent, good, medium, pass, fail }
    };
    
    // 调用AI服务生成报告
    const report = await generateAIReport(statistics);
    
    res.json({
      success: true,
      data: {
        statistics,
        report,
        generatedAt: new Date().toISOString()
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: 'AI报告生成失败',
      error: error.message
    });
  }
});

// 分类统计分析（支持课程和班级维度）
router.get('/classification', async (req, res) => {
  try {
    const { type, course: courseName, class: className } = req.query;
    
    // type: 'overall'(总体), 'by-class'(按班级), 'by-course'(按课程), 'cross'(交叉分析)
    const analysisType = type || 'overall';
    
    let result = {};
    
    switch (analysisType) {
      case 'overall':
        // 总体分类统计
        result = await getOverallClassification(courseName, className);
        break;
      
      case 'by-class':
        // 按班级分类统计
        result = await getClassificationByClass(courseName);
        break;
      
      case 'by-course':
        // 按课程分类统计
        result = await getClassificationByCourse(className);
        break;
      
      case 'cross':
        // 交叉分析（班级×课程）
        result = await getCrossClassification();
        break;
      
      default:
        return res.status(400).json({
          success: false,
          message: '无效的分析类型'
        });
    }
    
    res.json({
      success: true,
      data: result
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '分类统计分析失败',
      error: error.message
    });
  }
});

// 总体分类统计
async function getOverallClassification(courseName, className) {
  const query = className ? { class: className } : {};
  const students = await Student.find(query);
  
  const grades = { excellent: [], good: [], medium: [], pass: [], fail: [] };
  
  students.forEach(student => {
    if (!student.scores || student.scores.length === 0) return;
    
    let score;
    if (courseName) {
      const courseScore = student.scores.find(s => s.courseName === courseName);
      if (!courseScore) return;
      score = courseScore.score;
    } else {
      score = student.scores.reduce((sum, s) => sum + s.score, 0) / student.scores.length;
    }
    
    const studentInfo = {
      studentId: student.studentId,
      name: student.name,
      class: student.class,
      score: Number(score.toFixed(2))
    };
    
    if (score >= 90) grades.excellent.push(studentInfo);
    else if (score >= 80) grades.good.push(studentInfo);
    else if (score >= 70) grades.medium.push(studentInfo);
    else if (score >= 60) grades.pass.push(studentInfo);
    else grades.fail.push(studentInfo);
  });
  
  const total = students.length;
  
  return {
    type: 'overall',
    scope: {
      class: className || '全部班级',
      course: courseName || '平均成绩'
    },
    summary: {
      total,
      excellent: grades.excellent.length,
      good: grades.good.length,
      medium: grades.medium.length,
      pass: grades.pass.length,
      fail: grades.fail.length,
      excellentRate: ((grades.excellent.length / total) * 100).toFixed(2),
      goodRate: ((grades.good.length / total) * 100).toFixed(2),
      mediumRate: ((grades.medium.length / total) * 100).toFixed(2),
      passRate: ((grades.pass.length / total) * 100).toFixed(2),
      failRate: ((grades.fail.length / total) * 100).toFixed(2)
    },
    details: grades
  };
}

// 按班级分类统计
async function getClassificationByClass(courseName) {
  const students = await Student.find({});
  const classesList = [...new Set(students.map(s => s.class))];
  
  const classificationByClass = await Promise.all(
    classesList.map(async (cls) => {
      const classStudents = students.filter(s => s.class === cls);
      const grades = { excellent: 0, good: 0, medium: 0, pass: 0, fail: 0 };
      let totalScore = 0;
      let validCount = 0;
      
      classStudents.forEach(student => {
        if (!student.scores || student.scores.length === 0) return;
        
        let score;
        if (courseName) {
          const courseScore = student.scores.find(s => s.courseName === courseName);
          if (!courseScore) return;
          score = courseScore.score;
        } else {
          score = student.scores.reduce((sum, s) => sum + s.score, 0) / student.scores.length;
        }
        
        totalScore += score;
        validCount++;
        
        if (score >= 90) grades.excellent++;
        else if (score >= 80) grades.good++;
        else if (score >= 70) grades.medium++;
        else if (score >= 60) grades.pass++;
        else grades.fail++;
      });
      
      return {
        class: cls,
        total: validCount,
        average: validCount > 0 ? (totalScore / validCount).toFixed(2) : 0,
        distribution: grades,
        rates: {
          excellentRate: validCount > 0 ? ((grades.excellent / validCount) * 100).toFixed(2) : 0,
          goodRate: validCount > 0 ? ((grades.good / validCount) * 100).toFixed(2) : 0,
          mediumRate: validCount > 0 ? ((grades.medium / validCount) * 100).toFixed(2) : 0,
          passRate: validCount > 0 ? ((grades.pass / validCount) * 100).toFixed(2) : 0,
          failRate: validCount > 0 ? ((grades.fail / validCount) * 100).toFixed(2) : 0
        }
      };
    })
  );
  
  return {
    type: 'by-class',
    course: courseName || '平均成绩',
    data: classificationByClass.sort((a, b) => b.average - a.average)
  };
}

// 按课程分类统计
async function getClassificationByCourse(className) {
  const query = className ? { class: className } : {};
  const students = await Student.find(query);
  
  // 收集所有课程
  const coursesSet = new Set();
  students.forEach(student => {
    if (student.scores && student.scores.length > 0) {
      student.scores.forEach(s => coursesSet.add(s.courseName));
    }
  });
  
  const coursesList = Array.from(coursesSet);
  
  const classificationByCourse = coursesList.map(course => {
    const grades = { excellent: 0, good: 0, medium: 0, pass: 0, fail: 0 };
    let totalScore = 0;
    let validCount = 0;
    
    students.forEach(student => {
      if (!student.scores || student.scores.length === 0) return;
      
      const courseScore = student.scores.find(s => s.courseName === course);
      if (!courseScore) return;
      
      const score = courseScore.score;
      totalScore += score;
      validCount++;
      
      if (score >= 90) grades.excellent++;
      else if (score >= 80) grades.good++;
      else if (score >= 70) grades.medium++;
      else if (score >= 60) grades.pass++;
      else grades.fail++;
    });
    
    return {
      course,
      total: validCount,
      average: validCount > 0 ? (totalScore / validCount).toFixed(2) : 0,
      distribution: grades,
      rates: {
        excellentRate: validCount > 0 ? ((grades.excellent / validCount) * 100).toFixed(2) : 0,
        goodRate: validCount > 0 ? ((grades.good / validCount) * 100).toFixed(2) : 0,
        mediumRate: validCount > 0 ? ((grades.medium / validCount) * 100).toFixed(2) : 0,
        passRate: validCount > 0 ? ((grades.pass / validCount) * 100).toFixed(2) : 0,
        failRate: validCount > 0 ? ((grades.fail / validCount) * 100).toFixed(2) : 0
      }
    };
  });
  
  return {
    type: 'by-course',
    class: className || '全部班级',
    data: classificationByCourse.sort((a, b) => b.average - a.average)
  };
}

// 交叉分析（班级×课程）
async function getCrossClassification() {
  const students = await Student.find({});
  
  // 收集所有班级和课程
  const classesList = [...new Set(students.map(s => s.class))];
  const coursesSet = new Set();
  students.forEach(student => {
    if (student.scores && student.scores.length > 0) {
      student.scores.forEach(s => coursesSet.add(s.courseName));
    }
  });
  const coursesList = Array.from(coursesSet);
  
  // 构建交叉分析矩阵
  const matrix = classesList.map(cls => {
    const classData = {
      class: cls,
      courses: {}
    };
    
    coursesList.forEach(course => {
      const classStudents = students.filter(s => s.class === cls);
      const grades = { excellent: 0, good: 0, medium: 0, pass: 0, fail: 0 };
      let totalScore = 0;
      let validCount = 0;
      
      classStudents.forEach(student => {
        if (!student.scores || student.scores.length === 0) return;
        
        const courseScore = student.scores.find(s => s.courseName === course);
        if (!courseScore) return;
        
        const score = courseScore.score;
        totalScore += score;
        validCount++;
        
        if (score >= 90) grades.excellent++;
        else if (score >= 80) grades.good++;
        else if (score >= 70) grades.medium++;
        else if (score >= 60) grades.pass++;
        else grades.fail++;
      });
      
      classData.courses[course] = {
        total: validCount,
        average: validCount > 0 ? Number((totalScore / validCount).toFixed(2)) : 0,
        distribution: grades
      };
    });
    
    return classData;
  });
  
  return {
    type: 'cross',
    classes: classesList,
    courses: coursesList,
    matrix
  };
}

// 按班级对比分析
router.get('/class-comparison', async (req, res) => {
  try {
    const classStats = await Student.aggregate([
      {
        $group: {
          _id: '$class',
          count: { $sum: 1 },
          avgScore: { $avg: '$score' },
          maxScore: { $max: '$score' },
          minScore: { $min: '$score' }
        }
      },
      {
        $sort: { avgScore: -1 }
      }
    ]);
    
    // 计算每个班级的及格率和优秀率
    const detailedStats = await Promise.all(
      classStats.map(async (cls) => {
        const students = await Student.find({ class: cls._id });
        const total = students.length;
        const passCount = students.filter(s => s.score >= 60).length;
        const excellentCount = students.filter(s => s.score >= 90).length;
        
        return {
          class: cls._id,
          count: cls.count,
          average: Number(cls.avgScore.toFixed(2)),
          max: cls.maxScore,
          min: cls.minScore,
          passRate: Number(((passCount / total) * 100).toFixed(2)),
          excellentRate: Number(((excellentCount / total) * 100).toFixed(2))
        };
      })
    );
    
    res.json({
      success: true,
      data: detailedStats
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '班级对比分析失败',
      error: error.message
    });
  }
});

module.exports = router;
